<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane label="邮箱设置" name="email">
        <el-card>
          <div slot="header" class="clearfix">
            <span>邮箱配置</span>
            <el-button style="float: right; margin-left: 10px" type="primary" size="small"
              @click="saveEmailSettings">保存设置</el-button>
          </div>
          <el-form ref="emailForm" :model="emailSettings" label-width="120px" :rules="emailRules">
            <el-form-item label="邮件服务器" prop="host">
              <el-input v-model="emailSettings.host" placeholder="例如：smtp.example.com"></el-input>
            </el-form-item>
            <el-form-item label="服务器端口" prop="port">
              <el-input v-model="emailSettings.port" placeholder="例如：465"></el-input>
            </el-form-item>
            <el-form-item label="使用SSL" prop="secure">
              <el-switch v-model="emailSettings.secure" active-text="是" inactive-text="否"></el-switch>
            </el-form-item>
            <el-form-item label="邮箱账号" prop="auth_user">
              <el-input v-model="emailSettings.auth_user" placeholder="登录邮箱的用户名"></el-input>
            </el-form-item>
            <el-form-item label="邮箱密码" prop="auth_pass">
              <el-input v-model="emailSettings.auth_pass" type="password" placeholder="登录邮箱的密码"></el-input>
            </el-form-item>
            <el-form-item label="发件人名称" prop="from">
              <el-input v-model="emailSettings.from" placeholder="例如：IT猴社区 <noreply@example.com>"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="testEmailSettings">测试配置</el-button>
              <el-button @click="resetEmailSettings">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="短信设置" name="sms">
        <el-card>
          <div slot="header" class="clearfix">
            <span>阿里云短信配置</span>
            <el-button style="float: right; margin-left: 10px" type="primary" size="small"
              @click="saveSmsSettings">保存设置</el-button>
          </div>
          <el-form ref="smsForm" :model="smsSettings" label-width="140px" :rules="smsRules">
            <el-form-item label="AccessKey ID" prop="accessKeyId">
              <el-input v-model="smsSettings.accessKeyId" placeholder="阿里云AccessKey ID"></el-input>
            </el-form-item>
            <el-form-item label="AccessKey Secret" prop="accessKeySecret">
              <el-input v-model="smsSettings.accessKeySecret" type="password"
                placeholder="阿里云AccessKey Secret"></el-input>
            </el-form-item>
            <el-form-item label="短信签名" prop="signName">
              <el-input v-model="smsSettings.signName" placeholder="短信签名名称"></el-input>
            </el-form-item>
            <el-form-item label="注册验证码模板ID" prop="templateCode_register">
              <el-input v-model="smsSettings.templateCode_register" placeholder="例如：SMS_12345678"></el-input>
            </el-form-item>
            <el-form-item label="登录验证码模板ID" prop="templateCode_login">
              <el-input v-model="smsSettings.templateCode_login" placeholder="例如：SMS_87654321"></el-input>
            </el-form-item>
            <el-form-item label="重置密码模板ID" prop="templateCode_reset">
              <el-input v-model="smsSettings.templateCode_reset" placeholder="例如：SMS_11223344"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="testSmsSettings">测试配置</el-button>
              <el-button @click="resetSmsSettings">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 测试配置对话框 -->
    <el-dialog :title="testDialogTitle" :visible.sync="testDialogVisible" width="400px">
      <el-form :model="testForm" label-width="80px">
        <el-form-item :label="testType === 'email' ? '邮箱' : '手机号'" prop="receiver">
          <el-input v-model="testForm.receiver" :placeholder="testType === 'email' ? '请输入测试邮箱' : '请输入测试手机号'"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="testDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="sendTestMessage" :loading="testLoading">发送测试</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getSettings, updateSettings, sendEmailCode, sendSMSCode } from '@/api/system/settings'

export default {
  name: 'SystemSettings',
  data() {
    return {
      activeTab: 'email',
      loading: false,
      // 邮箱设置
      emailSettings: {
        host: '',
        port: '',
        secure: true,
        auth_user: '',
        auth_pass: '',
        from: ''
      },
      // 短信设置
      smsSettings: {
        accessKeyId: '',
        accessKeySecret: '',
        signName: '',
        templateCode_register: '',
        templateCode_login: '',
        templateCode_reset: ''
      },
      // 表单验证规则
      emailRules: {
        host: [{ required: true, message: '请输入邮件服务器地址', trigger: 'blur' }],
        port: [{ required: true, message: '请输入服务器端口', trigger: 'blur' }],
        auth_user: [{ required: true, message: '请输入邮箱账号', trigger: 'blur' }],
        from: [{ required: true, message: '请输入发件人名称', trigger: 'blur' }]
      },
      smsRules: {
        accessKeyId: [{ required: true, message: '请输入AccessKey ID', trigger: 'blur' }],
        signName: [{ required: true, message: '请输入短信签名', trigger: 'blur' }],
        templateCode_register: [{ required: true, message: '请输入注册验证码模板ID', trigger: 'blur' }],
        templateCode_login: [{ required: true, message: '请输入登录验证码模板ID', trigger: 'blur' }],
        templateCode_reset: [{ required: true, message: '请输入重置密码模板ID', trigger: 'blur' }]
      },
      // 测试对话框
      testDialogVisible: false,
      testDialogTitle: '测试邮箱配置',
      testType: 'email',
      testForm: {
        receiver: ''
      },
      testLoading: false,
      // 原始设置备份
      originalEmailSettings: {},
      originalSmsSettings: {}
    }
  },
  created() {
    this.fetchSettings()
  },
  methods: {
    // 获取设置
    fetchSettings() {
      this.loading = true
      getSettings().then(response => {
        const { data } = response

        if (data) {
          // 处理邮箱设置
          if (data.email) {
            const emailSettings = {}
            Object.keys(data.email).forEach(key => {
              emailSettings[key] = data.email[key].key_value
            })

            this.emailSettings = {
              host: emailSettings.host || '',
              port: emailSettings.port || '',
              secure: emailSettings.secure === '1',
              auth_user: emailSettings.auth_user || '',
              auth_pass: emailSettings.auth_pass || '',
              from: emailSettings.from || ''
            }

            // 备份原始设置
            this.originalEmailSettings = JSON.parse(JSON.stringify(this.emailSettings))
          }

          // 处理短信设置
          if (data.sms) {
            const smsSettings = {}
            Object.keys(data.sms).forEach(key => {
              smsSettings[key] = data.sms[key].key_value
            })

            this.smsSettings = {
              accessKeyId: smsSettings.accessKeyId || '',
              accessKeySecret: smsSettings.accessKeySecret || '',
              signName: smsSettings.signName || '',
              templateCode_register: smsSettings.templateCode_register || '',
              templateCode_login: smsSettings.templateCode_login || '',
              templateCode_reset: smsSettings.templateCode_reset || ''
            }

            // 备份原始设置
            this.originalSmsSettings = JSON.parse(JSON.stringify(this.smsSettings))
          }
        }
      }).catch(error => {
        console.error('获取设置失败:', error)
        this.$message.error('获取设置失败')
      }).finally(() => {
        this.loading = false
      })
    },

    // 保存邮箱设置
    saveEmailSettings() {
      this.$refs.emailForm.validate(valid => {
        if (valid) {
          this.loading = true

          // 准备要更新的数据
          const settings = {
            host: this.emailSettings.host,
            port: this.emailSettings.port,
            secure: this.emailSettings.secure ? '1' : '0',
            auth_user: this.emailSettings.auth_user,
            from: this.emailSettings.from
          }

          // 如果密码已修改，则更新密码
          if (this.emailSettings.auth_pass && this.emailSettings.auth_pass !== '******') {
            settings.auth_pass = this.emailSettings.auth_pass
          }

          updateSettings({
            category: 'email',
            settings
          }).then(response => {
            const { data, code } = response

            if (code === 200) {
              this.$message.success('邮箱设置保存成功')
              // 更新备份
              this.originalEmailSettings = JSON.parse(JSON.stringify(this.emailSettings))
              // 重新获取设置
              this.fetchSettings()
            } else {
              this.$message.error(data.msg || '保存失败')
            }
          }).catch(error => {
            console.error('保存设置失败:', error)
            this.$message.error('保存设置失败')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },

    // 保存短信设置
    saveSmsSettings() {
      this.$refs.smsForm.validate(valid => {
        if (valid) {
          this.loading = true

          // 准备要更新的数据
          const settings = {
            accessKeyId: this.smsSettings.accessKeyId,
            signName: this.smsSettings.signName,
            templateCode_register: this.smsSettings.templateCode_register,
            templateCode_login: this.smsSettings.templateCode_login,
            templateCode_reset: this.smsSettings.templateCode_reset
          }

          // 如果密钥已修改，则更新密钥
          if (this.smsSettings.accessKeySecret && this.smsSettings.accessKeySecret !== '******') {
            settings.accessKeySecret = this.smsSettings.accessKeySecret
          }

          updateSettings({
            category: 'sms',
            settings
          }).then(response => {
            const { data } = response
            if (data.code === 200) {
              this.$message.success('短信设置保存成功')
              // 更新备份
              this.originalSmsSettings = JSON.parse(JSON.stringify(this.smsSettings))
              // 重新获取设置
              this.fetchSettings()
            } else {
              this.$message.error(data.msg || '保存失败')
            }
          }).catch(error => {
            console.error('保存设置失败:', error)
            this.$message.error('保存设置失败')
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },

    // 测试邮箱设置
    testEmailSettings() {
      this.$refs.emailForm.validate(valid => {
        if (valid) {
          this.testType = 'email'
          this.testDialogTitle = '测试邮箱配置'
          this.testForm.receiver = ''
          this.testDialogVisible = true
        }
      })
    },

    // 测试短信设置
    testSmsSettings() {
      this.$refs.smsForm.validate(valid => {
        if (valid) {
          this.testType = 'sms'
          this.testDialogTitle = '测试短信配置'
          this.testForm.receiver = ''
          this.testDialogVisible = true
        }
      })
    },

    // 发送测试消息
    sendTestMessage() {
      if (!this.testForm.receiver) {
        this.$message.warning(this.testType === 'email' ? '请输入测试邮箱' : '请输入测试手机号')
        return
      }

      this.testLoading = true

      const params = this.testType === 'email'
        ? { email: this.testForm.receiver, purpose: 'login' }
        : { phone: this.testForm.receiver, purpose: 'login' }

      const apiMethod = this.testType === 'email' ? sendEmailCode : sendSMSCode

      apiMethod(params).then(response => {
        const { data, code, msg } = response
        if (code === 200) {
          this.$message.success('测试消息发送成功')
          this.testDialogVisible = false
        } else {
          this.$message.error(msg || '发送失败')
        }
      }).catch(error => {
        console.error('发送测试消息失败:', error)
        this.$message.error('发送测试消息失败')
      }).finally(() => {
        this.testLoading = false
      })
    },

    // 重置邮箱设置
    resetEmailSettings() {
      this.emailSettings = JSON.parse(JSON.stringify(this.originalEmailSettings))
    },

    // 重置短信设置
    resetSmsSettings() {
      this.smsSettings = JSON.parse(JSON.stringify(this.originalSmsSettings))
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-card {
  margin-bottom: 20px;
}
</style>